//
//  PHAsset+UIImage.m
//  Meiyu
//
//  Created by apple on 16/8/26.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "PHAsset+UIImage.h"

#define kThumbnailImageSize (CGSize){100, 100}

@implementation PHAsset (UIImage)

- (void)getVideoAssetFirstFrameImage:(void (^)(UIImage *))completion
{
    [self getImageAssetThumbnailImage:completion];
}

- (void)fetchVideoWithProgressHandler:(void (^)(double))progressHandler
                    completionHandler:(void (^)(AVAsset *))completionHandler
{
    PHVideoRequestOptions *request = [PHVideoRequestOptions new];
    request.deliveryMode = PHVideoRequestOptionsDeliveryModeMediumQualityFormat;
    request.version = PHVideoRequestOptionsVersionCurrent;
    
    /*
     * networkAccessAllowed
     * A Boolean value indicating whether the photo asset data is stored on the local device or must be
     * downloaded from iCloud. (NSNumber)
     *
     * If YES, no image was provided, because the asset data must be downloaded from iCloud. To download the
     * data, submit another request, and specify YES for the networkAccessAllowed option.
     */
    
    request.networkAccessAllowed = YES;
    request.progressHandler = ^ (double progress, NSError * error, BOOL *stop, NSDictionary * info) {
        RunAsyncOnMain(^{
            progressHandler(progress);
        });
    };
    
    [[PHImageManager defaultManager] requestAVAssetForVideo:self
                                                    options:request
                                              resultHandler:
     ^(AVAsset* asset, AVAudioMix* audioMix, NSDictionary* info) {
         RunAsyncOnMain(^{
             completionHandler(asset);
         });
     }];
}

- (void)getImageAssetImageWithImageSize:(CGSize)imageViewSize
                             completion:(void (^)(UIImage *))completion
{
    NSString *identifier = [NSString stringWithFormat:@"%@_%@", self.localIdentifier, NSStringFromCGSize(imageViewSize)];
    
    UIImage *image = [[SDImageCache sharedImageCache] imageFromMemoryCacheForKey:identifier];
    if (image) {
        completion(image);
        return;
    }

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.synchronous = YES;
    options.networkAccessAllowed = YES;
    
    [[PHImageManager defaultManager] requestImageForAsset:self
                                               targetSize:imageViewSize
                                              contentMode:PHImageContentModeAspectFill
                                                  options:options
                                            resultHandler:^(UIImage *image, NSDictionary *info) {
                                                if (image) {
                                                    [[SDImageCache sharedImageCache] storeImage:image forKey:identifier completion:nil];
                                                    RunAsyncOnMain(^{
                                                        completion(image);
                                                    });
                                                }
                                            }];
}

- (void)getImageAssetThumbnailImage:(void (^)(UIImage *))completion
{
    [self getImageAssetImageWithImageSize:kThumbnailImageSize completion:completion];
}

- (void)getImageAssetOriginalImage:(void (^)(UIImage *))completion
{
    [self getImageAssetImageWithImageSize:PHImageManagerMaximumSize completion:completion];
}

+ (PHAsset *)fetchPHAssetWithUrl:(NSURL *)url
{
    PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
    PHAsset *asset = result.firstObject;

    return asset;
}


@end
